package com.weilele.mvvm.utils.shortcut

import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import android.os.Build
import androidx.annotation.DrawableRes
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat
import com.weilele.mvvm.app
import kotlin.math.min

data class ShortcutBean(
    val id: String,
    val jumpCls: Class<*>?,
    val shortTitle: String,
    val longTitle: String,
    val disableTitle: String,
    @DrawableRes val icon: Int,
    val block: Function1<ShortcutInfoCompat.Builder, Unit>?,
)

/**
 * 设置一组ShortsCuts
 */
fun setShortsCuts(shortcutInfo: MutableList<ShortcutBean>) {
    val results = initShortsCut(shortcutInfo)
    if (!results.isNullOrEmpty()) {
        ShortcutManagerCompat.setDynamicShortcuts(app, results)
    }
}

/**
 * 移除一组ShortsCuts
 */
fun removeShortcuts(shortcutInfo: MutableList<ShortcutBean>) {
    val results = initShortsCut(shortcutInfo)
    if (!results.isNullOrEmpty()) {
        ShortcutManagerCompat.removeDynamicShortcuts(app, shortcutInfo.map { it.id })
    }
}

/**
 * 更新Shortcut
 */
fun updateShortcuts(shortcutInfo: MutableList<ShortcutBean>) {
    val results = initShortsCut(shortcutInfo)
    if (!results.isNullOrEmpty()) {
        ShortcutManagerCompat.updateShortcuts(app, results)
    }
}

/**
 * 设置动态shortcut
 */
private fun initShortsCut(shortcutInfo: MutableList<ShortcutBean>): MutableList<ShortcutInfoCompat>? {
    val maxCount = ShortcutManagerCompat.getMaxShortcutCountPerActivity(app)
    val dynamicShortcuts: MutableList<ShortcutInfoCompat> = mutableListOf()
    repeat(min(shortcutInfo.count(), maxCount)) {
        val bean = shortcutInfo[it]
        val infoBuild = ShortcutInfoCompat.Builder(app, bean.id) //设置id
            .setShortLabel(bean.shortTitle) //设置短标题
            .setLongLabel(bean.longTitle) //设置长标题
            .setDisabledMessage(bean.disableTitle) //设置长标题
            .setIcon(IconCompat.createWithResource(app, bean.icon)) //设置图标
        if (bean.jumpCls != null) {
            val intent = Intent(app, bean.jumpCls)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            intent.action = Intent.ACTION_VIEW
            infoBuild.setIntent(intent) //设置intent
        }
        if (bean.block != null) {
            bean.block.invoke(infoBuild)
        }
        dynamicShortcuts.add(infoBuild.build())
    }
    return dynamicShortcuts
}

/**
 * android 11 处理方案，参考此文章（https://blog.csdn.net/u010844304/article/details/111044338）
 * <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>
 */
data class AppInfoBean(
    val name: CharSequence,
    val icon: Drawable
)

//获取当前手机安装的应用列表
@SuppressLint("QueryPermissionsNeeded")
fun getAllInstallAppInfo(): List<AppInfoBean> {
    val pm = app.packageManager
    // 获取到所有安装了的应用程序的信息，包括那些卸载了的，但没有清除数据的应用程序
    val infos = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        pm.getInstalledPackages(PackageManager.MATCH_UNINSTALLED_PACKAGES)
    } else {
        pm.getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES)
    }
    return infos.map {
        val appName = it.applicationInfo.loadLabel(pm)
        val icon = it.applicationInfo.loadIcon(pm)
        AppInfoBean(appName, icon)
    }
}

/**
 * 通过包名查询是否安装了app
 * packageName
 */
fun String?.isAppInstalled(): Boolean {
    this ?: return false
    val manager = app.packageManager
    return manager?.getLaunchIntentForPackage(this) != null
}
